﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoAnWebsite.Models;
using Ext.Net;
using Ext.Net.MVC;
using System.Linq.Dynamic;

namespace DoAnWebsite.Controllers
{
    public class NewsController : Controller
    {
        //News
        private static DoAnWebsite_Entities db = new DoAnWebsite_Entities();

        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult ListNews()
        {
            Session["includeInActiveNews"] = false;
            Session["CharFilterNews"] = "";
            return View();
        }

        public ActionResult IncludeInActive()
        {
            var store = X.GetCmp<Store>("NewsStore");

            Session["includeInActiveNews"] = !(bool)Session["includeInActiveNews"];

            store.Reload();
            return this.Direct();
        }

        [DirectMethod]
        public ActionResult CharFilterNews(string filterstring)
        {
            var store = X.GetCmp<Store>("NewsStore");
            Session["CharFilterNews"] = filterstring;
            store.Reload();
            return this.Direct();
        }

        public ActionResult BindingNewsStore(StoreRequestParameters parameters)
        {
            var sampleData = (db.News.Join(db.GroupNews, tab1 => tab1.GroupNewsId, tab2 => tab2.GroupNewsId,
                                           (tab1, tab2) => new
                                           {
                                               tab1.NewsId,
                                               tab1.Name,
                                               tab1.Date,
                                               tab1.Title,
                                               tab2.GNName,
                                               tab1.Views,
                                               tab1.CreateBy,
                                               tab1.Active
                                           })
                             );
            if (User.IsInRole("users"))
            {
                sampleData = sampleData.Where(x => User.Identity.Name.ToUpper().Equals(x.CreateBy.ToUpper()));
            }


            bool includeInActive = (bool)Session["includeInActiveNews"];
            string charFilter = (string)Session["CharFilterNews"];

            var result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active)));
            if ("0".Equals(charFilter))
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) &&
                    (ent.Name.StartsWith("0") || ent.Name.StartsWith("1") ||
                    ent.Name.StartsWith("2") || ent.Name.StartsWith("3") ||
                    ent.Name.StartsWith("4") || ent.Name.StartsWith("5") ||
                    ent.Name.StartsWith("6") || ent.Name.StartsWith("7") ||
                    ent.Name.StartsWith("8") || ent.Name.StartsWith("9")
                    )));
            }

            else
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) && ent.Name.StartsWith(charFilter)));

            }

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.NewsId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData.Select(ent => new { ent.NewsId, ent.Name, ent.Date, ent.Title, ent.GNName, ent.Views,ent.CreateBy, ent.Active }), result.Count());
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult CreateNews()
        {
            ViewBag.HideTextBox = false;
            ViewBag.GNewsId = new List<ListItem>();
            ViewBag.GNewsId = db.GroupNews.ToList().Select(ent => new ListItem { Text = ent.GNName, Value = ent.GroupNewsId.ToString() });
            ViewBag.CancerId = new List<ListItem>();
            ViewBag.CancerId = db.Cancers.ToList().Select(ent => new ListItem { Text = ent.CancerName, Value = ent.CancerId.ToString() });

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateNews(News model)
        {
            if (ModelState.IsValid)
            {
                var upImage = X.GetCmp<FileUploadField>("UpImage");
                if (upImage.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadImage//" +
                                                  httpPostedFileBase.FileName);
                        model.Image = "/Content/UploadImage/" + httpPostedFileBase.FileName;
                    }
                }
                
                News news = db.News.SingleOrDefault(m => m.Home && (m.GroupNewsId == model.GroupNewsId));
                if (news != null)
                {
                    news.Home = false;
                    db.SaveChanges();
                }
                model.Home = true;

                //add Tag
                string[] s = model.Keyword.Split(',');
                for (int i = 0; i < s.Length; i++)
                {
                    string si = s[i];
                    var tag = db.Tags.SingleOrDefault(x => si.Equals(x.TagString));
                    if(tag!=null) model.Tags.Add(tag);
                    else
                    {
                        var temp = new Tag();
                        temp.TagString = s[i];
                        db.Tags.AddObject(temp);
                        db.SaveChanges();
                        model.Tags.Add(temp);
                    }
                }

                model.CreateBy = User.Identity.Name;
                model.Views = 0;
                model.Active = true;
                db.News.AddObject(model);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Create News success!").Show();
                return this.FormPanel();
            }

            X.Msg.Notify("Non Sucess", "Create News non success!").Show();

            return this.FormPanel();
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult EditNews(int id)
        {
            ViewBag.HideTextBox = false;
            ViewBag.GNewsId = new List<ListItem>();
            ViewBag.GNewsId = db.GroupNews.ToList().Select(ent => new ListItem { Text = ent.GNName, Value = ent.GroupNewsId.ToString() });
            ViewBag.CancerId = new List<ListItem>();
            ViewBag.CancerId = db.Cancers.ToList().Select(ent => new ListItem { Text = ent.CancerName, Value = ent.CancerId.ToString() });

            News news = db.News.Single(m => m.NewsId == id);
            return View(news);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditNews(News model)
        {
            News news1 = db.News.Single(c => c.NewsId == model.NewsId);
            if (ModelState.IsValid)
            {
                var upImage = X.GetCmp<FileUploadField>("UpImage");
                if (upImage.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadImage//" +
                                                  httpPostedFileBase.FileName);
                        model.Image = "/Content/UploadImage/" + httpPostedFileBase.FileName;
                    }
                }
                else
                {
                    model.Image = news1.Image;
                }

                if(news1.Home && model.Home==false)
                {
                    var newHome =
                        db.News.Where(m => m.GroupNewsId == model.GroupNewsId && m.NewsId != model.NewsId).OrderBy(
                            m => m.Date).Take(1);
                    var firstOrDefault = newHome.FirstOrDefault();
                    if (firstOrDefault != null)
                    {
                        firstOrDefault.Home =true;
                        db.SaveChanges();
                    }
                }
                else if (news1.Home==false && model.Home)
                {
                    var oldHome = db.News.SingleOrDefault(m => m.GroupNewsId == model.GroupNewsId && m.Home);
                    if (oldHome != null)
                    {
                        oldHome.Home = false;
                        db.SaveChanges();
                    }
                }
                
                db.News.Detach(news1);
                db.News.Attach(model);
                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Edit GroupNews success!").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Non Sucess", "Edit GroupNews non success!").Show();
            return this.FormPanel();
        }


        //add Tag
        public void AddTag(string keyword, int newsId)
        {
        }

    }
}
